package net.godbirds.boot.common.datasource;

import java.sql.Connection;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 动态数据源切换
 * @author Darker.Wang
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
	private static int MAX_CHECK_TIMES = 10;//重复获取连接次数
	private static int START_CHECK = 0;
    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSourceType();
    }
    
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    public static void setDataSourceType(String dataSourceType) {
        contextHolder.set(dataSourceType);
    }

    public static String getDataSourceType() {
        return contextHolder.get();
    }

    public static void clearDataSourceType() {
        contextHolder.remove();
    }
    public static void recover(){
    	setDataSourceType("ds");
    }
    /**
	 * 校验连接是否可用
	 * @param dbType
	 * @return
	 */
	public boolean checkConnection(String dbType){
		boolean result = false;
		try{
			START_CHECK ++;
			System.out.println("- Get And Check Connection : "+START_CHECK);
			setDataSourceType(dbType);
			Connection conn = this.getConnection();
			if(conn == null){
				System.out.println("- There is no connection from datasorce named "+dbType);
				System.out.println("- Check Connection : "+result);
				return false;
			}
			//备注：若换库，则此处需要修改为对应的可执行的语句
			conn.createStatement().execute("select 1 from dual");
			conn.close();//关闭连接
			result = true;
			System.out.println("- Check Connection : "+result);
			return result;
		}catch(Exception e){
			System.out.println("- Get "+ dbType+ " Connection Fail cause : "+e.getMessage());
			System.out.println("- And "+ dbType+ " Connection Regoting ... ");
			if(START_CHECK <= MAX_CHECK_TIMES){
				result = checkConnection(dbType);
			}else{
				System.out.println("- "+MAX_CHECK_TIMES+" 次获取连接都没成功，结束");
				START_CHECK = 0;//置0 以待下次使用
				System.out.println("- Check Connection : "+result);
				return result;
			}
		}
		System.out.println("- Check Connection : "+result);
		START_CHECK = 0;//置0 以待下次使用
		return result;
	}
}